#ifndef TCPNET_H_
#define TCPNET_H_
/*********************************************************/
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/ThreadPool.h"
#include "Poco/Mutex.h"
#include <string>
#include <vector>

class TCPNet;
/*********************************************************/
class TCPConnection : public Poco::Net::TCPServerConnection
{
private:
	TCPNet*		net;
public:
	// Methods
	void run();			// Handle the connection
	void setTCPNet(TCPNet*);	// Sets the TCPNet ( all messages will be added to this TCPNet's queue )

	// Constructor
	TCPConnection(const Poco::Net::StreamSocket& s) : TCPServerConnection(s){}	// Constructor for a TCPConnection
};
/*********************************************************/
class TCPConnectionFactory : public Poco::Net::TCPServerConnectionFactory
{
private:
	TCPNet*		masterClass;		// A Pointer to the master class controlling this TCPServer
public:
	// Methods
	TCPConnection* createConnection(const Poco::Net::StreamSocket& socket);

	// Construction
	TCPConnectionFactory(TCPNet* net) : masterClass(net) {};
};
/*********************************************************/
class TCPNet
{
private:
	// Member Objects
	Poco::Net::ServerSocket* 	listener;		// listener socket, to listen for incoming connections
	Poco::Net::StreamSocket*	sender;			// Socket to send data on
	Poco::Net::SocketAddress	localAddr;		// Local address of the server
	Poco::Net::TCPServer*		tcpServer;		// Server listening for & servicing connections
	TCPConnectionFactory*		factory;		// Factory creating the seperate connection objects
	Poco::ThreadPool		tPool;			// Thread pool used for the tcp server
	Poco::Mutex			mQueue;			// Mutex used to secure the arriving message queue
	std::vector<std::string>	queue;			// incoming message queue

	// Methods
	void enqueue(const std::string&);			// Puts an incoming message into the queue

	// Friend declarations
	friend class TCPConnection;

protected:
public:
	// Methods
	void connect(const std::string& host, const int& port);	// connects the streamsocket
	void disconnect();					// Disconnects the streamsocket
	bool available();					// Returns if any messages are in the message queue
	std::string pop();					// Pops the front of the queue
	
	// Construction & Destruction
	TCPNet(const std::string& host, const int& port);
	~TCPNet();
};
/*********************************************************/
#endif // TCPNET_H_